﻿using System;
using System.Runtime.Caching;

namespace Tools {
    public class LocalMemoryCache {

        private static readonly MemoryCache LocalMemory = MemoryCache.Default;

        public static bool Contains(string key) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
            return LocalMemory.Contains(key);
        }

        /// <summary>
        /// 设置本地缓存，上层捕获并封装异常
        /// Eg:    
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一关键字</param>
        /// <param name="data">数据</param>
        /// <param name="dateTimeOffset">过期时间为NULL，默认时间为30min</param>
        /// <returns></returns>
        public static void SetCache(string key, object data, DateTimeOffset dateTimeOffset) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));

            LocalMemory.Set(key, data, dateTimeOffset);
        }

        /// <summary>
        /// 设置本地缓存，上层捕获并封装异常
        /// Eg:    
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一关键字</param>
        /// <param name="data">数据</param>
        public static void SetCache(string key, object data) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
            SetCache(key, data, DateTimeOffset.Now.AddMinutes(30));
        }
        /// <summary>
        /// 设置本地缓存，上层捕获并封装异常
        /// Eg:    
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一关键字</param>
        /// <param name="data">数据</param>
        /// <param name="minutes">设置失效时间，单位为分钟</param>
        public static void SetCache(string key, object data, int minutes) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
            SetCache(key, data, DateTimeOffset.Now.AddMinutes(minutes));
        }
        /// <summary>
        ///     获取本地缓存中的数据
        ///     Key:User-Userid 保存用户主键
        ///     Key:UserPermission-Userid 保存用户权限值
        /// </summary>
        /// <param name="key">唯一标识</param>
        /// <returns>缓存中的数据，NULL表示不存在</returns>
        public static object GetCache(string key) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
            return LocalMemory.Get(key);
        }

        public static void Remove(string key) {
            if (String.IsNullOrEmpty(key)) throw new ArgumentNullException(nameof(key));
            LocalMemory.Remove(key);
        }
    }
}